<?php
namespace App\Imports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Dcat\Admin\Admin;
use Illuminate\Support\Facades\Redis;
use App\Models\Cabinet;
use App\Models\CabinetPoint;
use App\Models\CabinetAlarm;
use Illuminate\Support\Facades\DB;

class AlarmSettingImport implements ToCollection, WithChunkReading, WithHeadingRow
{
    protected $box;
    protected $cabinets;

    public function __construct($boxId) {
        $this->box = Cabinet::find($boxId);
        $this->cabinets = Cabinet::where('pid', $boxId)->pluck('id')->toArray();
    }

    public function collection(Collection $rows)
    {   
        $insertData = [];

        foreach ($rows->all() as $oneRow) {
            if (!in_array($oneRow['cabinet_id'], $this->cabinets)) {
                continue;
            }

            if (!in_array(trim($oneRow['condition']), CabinetAlarm::CONDITION)) {
                continue;
            }

            $one['project_id'] = $this->box['project_id'];
            $one['cabinet_pid'] = $this->box['id'];
            $one['cabinet_id'] = $oneRow['cabinet_id'];
            $one['point_id'] = $oneRow['point_id'];
            $one['name'] = trim($oneRow['name']);
            $one['level'] = intval($oneRow['level']);
            $one['value'] = round($oneRow['value'], 3);
            $one['condition'] = trim($oneRow['condition']);
            $one['active'] = intval($oneRow['active']);
            $one['map_alarm'] = intval($oneRow['map_alarm']);

            array_push($insertData, $one);
        }

        if ($insertData) {
            $table = env('DB_PREFIX').CabinetAlarm::getModel()->getTable();
            DB::table($table)->insert($insertData);
        }
    }

    public function chunkSize(): int
    {
        return 3000;
    }
}